﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;

namespace VSM
{
    public partial class APInvoice : System.Web.UI.Page
    {
        //public static DataTable dtContents;
        //public static DataTable dtHeader;
        //private static GeneralFunctions GF = null;
        
        private string TblHeaderName = "OPCH";
        private string TblLineName = "PCH1";
        private string CurrentPageUrl = "/Business/Purchasing/APInvoice.aspx";
        private string HeaderKeyName = "DocEntry";

        //private String TargetPageUrl = "/Business/Purchasing/CreatePO.aspx";
        //public static string KeepColumsContent = "";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }

            try
            {
                if (!IsPostBack)
                {
                    ClearScreen();
                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    Session["APGF"] = GF;

                    String apinvId = Request.QueryString["apinv_id"];
                    if (!String.IsNullOrEmpty(apinvId))
                    {
                        LoadData(apinvId, ConvertDocType.Get2String(DocType.AP_INVOICE) );
                        if (lblStatus.Text == "C")
                            SetScreenStatus("Close");
                        else if (lblStatus.Text == "O")
                            SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }
                    String BaseEntry = Request.QueryString["base_entry"];
                    if (!String.IsNullOrEmpty(BaseEntry))
                    {
                        String BaseType = Request.QueryString["base_type"];
                        LoadData(BaseEntry, BaseType);
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);            
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPCH1.PageIndex = e.NewPageIndex;
            DataTable tblIPCH1 = (DataTable)Session["PCH1Table"];
            BindData(tblIPCH1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["PCH1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString())) dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                        }
                        tb.Rows.Remove(rupdate[0]);
                        int liNo = 1;
                        foreach (DataRow dr in tb.Rows) // reset detail No. line
                        {
                            dr["No"] = liNo;
                            liNo++;
                        }
                    }
                    this.grvPCH1.EditIndex = -1;
                    BindData((DataTable)Session["PCH1Table"]);
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                GeneralFunctions GF = (GeneralFunctions)Session["APGF"];

                //
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label lblModel = (Label)e.Row.FindControl("lblModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (lblModel != null) ddlModel.SelectedValue = lblModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, lblModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label lblProduct = (Label)e.Row.FindControl("lblProduct");
                    if (lblProduct != null) ddlProduct.SelectedValue = lblProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label lblColor = (Label)e.Row.FindControl("lblColor");
                    if (lblColor != null) ddlColor.SelectedValue = lblColor.Text;
                }
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PCH1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                        updateRowTotalPrice(rupdate[0]);
                    }
                }

                this.grvPCH1.EditIndex = -1;
                
                BindData(tb);
                //CalcTotal(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input txtUnitPrice');", true);
                    txtUnitPrice.Focus();
                    return;
                }

                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PCH1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        //GetPrice(rupdate[0]);
                        updateRowTotalPrice(rupdate[0]);
                    }
                }

                this.grvPCH1.EditIndex = -1;
                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PCH1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        GetPrice(rupdate[0]);
                        updateRowTotalPrice(rupdate[0]);
                    }
                }

                this.grvPCH1.EditIndex = -1;
                BindData(tb);
                updateTableTotalPrice();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtDistNumber_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDistNumber = (TextBox)row.FindControl("txtDistNumber");

                if (txtDistNumber.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input VIN Number');", true);
                    txtDistNumber.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PCH1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DistNumber"] = txtDistNumber.Text.Trim();
                        rupdate[0]["InDate"] = txtPostingDate.Text;
                    }
                }

                this.grvPCH1.EditIndex = -1;
                BindData(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtEngineNumber_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtEngineNumber = (TextBox)row.FindControl("txtEngineNumber");

                if (txtEngineNumber.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input Engine Number');", true);
                    txtEngineNumber.Focus();
                    return;
                }

                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PCH1Table"];

                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0) rupdate[0]["Notes"] = txtEngineNumber.Text.Trim();
                }

                this.grvPCH1.EditIndex = -1;
                BindData(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dr"></param>
        private DataRow FillShipToAddress(string outletId, bool isFill)
        {
            //try
            //{
            //    if (outletId.Length > 0)
            //    {
            //        MasterData obj = new MasterData();
            //        DataSet tbWareHouse = null; // obj.GetWareHouseAddress(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode);
            //        if (tbWareHouse != null && tbWareHouse.Tables.Count > 0)
            //        {

            //            DataRow[] r = tbWareHouse.Tables[0].Select("WhsCode = '" + outletId + "'");
            //            if (r.Length > 0)
            //            {
            //                if (isFill)
            //                {
            //                    StringBuilder shipTo = new StringBuilder();
            //                    shipTo.AppendLine(r[0]["Block"].ToString());
            //                    shipTo.AppendLine(r[0]["Street"].ToString() + " " + r[0]["City"].ToString());
            //                    shipTo.AppendLine(r[0]["Country"].ToString() + " " + r[0]["ZipCode"].ToString());
            //                }
            //                else
            //                {
            //                    return r[0];
            //                }
            //            }
            //        }
            //    }

            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //    this.lblError.Visible = true;
            //}
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvPCH1.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["PCH1Table"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvPCH1.EditIndex = -1;
            BindData((DataTable)Session["PCH1Table"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvPCH1.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["PCH1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPCH1.EditIndex = -1;
                    BindData((DataTable)Session["PCH1Table"]);
                    //CalcTotal(((DataTable)Session["PCH1Table"]));
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvPCH1.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["PCH1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }

                    this.grvPCH1.EditIndex = -1;

                    BindData(tb);
                    //CalcTotal(tb);
                    updateTableTotalPrice();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["PCH1Table"] = tblData;
            this.grvPCH1.DataSource = tblData;
            this.grvPCH1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(string.IsNullOrEmpty(this.txtPostingDate.Text.Trim()) ? DateTime.Now.ToString("dd/MM/yyyy") : this.txtPostingDate.Text.Trim());

                    DataTable tblIPCH1 = (DataTable)Session["PCH1Table"];
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblIPCH1 != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow rowNew = tblIPCH1.NewRow();
                                        rowNew["No"] = (tblIPCH1.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        rowNew["U_Model"] =
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        //rowNew["DiscPrcnt"] = 0;
                                        rowNew["PriceBefDi"] =
                                        rowNew["U_Discount"] =
                                        rowNew["U_IncentiveDiscount"] =
                                        rowNew["PriceBefDi"] = 
                                        rowNew["VatPrcnt"] = 0;
                                        rowNew["TaxCode"] = string.Empty;
                                        tblIPCH1.Rows.Add(rowNew);
                                    }
                                    //ReLoad Data
                                    //BindData(tblIPCH1);
                                    if (tblIPCH1.Rows.Count > 0)
                                    {
                                        //Update Price
                                        UpdatePrice();
                                        //CalcTotal(tblIPO);
                                        updateTableTotalPrice();
                                    }   
                                }
                            }
                            //ReLoad Data
                            BindData(tblIPCH1);
                            break;
                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;
                            this.txtVendorCode.Text = ((Label)row.FindControl("lblCardCode")).Text;
                            this.txtVendorName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            if (tblIPCH1 != null) tblIPCH1.Rows.Clear();
                            Session["ChosenBP"] = null;
                            this.btnAddItems.Visible = true;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string poId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            LoadData(poId, doctype);
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="tblIPO"></param>
        /// <returns></returns>
        private DataTable LoadSetupItem(DateTime poDate, DataTable tblIPO)
        {
            MasterData obj = new MasterData();
            DataSet dsItem = null; // obj.GetSupplierItemSetup(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, this.txtVendorCode.Text, "");
            Dictionary<string, string> dicItem = new Dictionary<string, string>();
            if (dsItem != null && dsItem.Tables.Count > 0)
            {
                dsItem.Tables[0].Columns.Add("Quantity");
                DataSet dsAllPrice = null;//obj.GetAllItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, this.txtVendorCode.Text,dsItem.Tables[0]);
                foreach (DataRow r in dsItem.Tables[0].Rows)
                {
                    if (!dicItem.ContainsKey(r["ItemCode"].ToString()))
                    {
                        dicItem.Add(r["ItemCode"].ToString(), r["ItemName"].ToString());
                    }
                    if (dsAllPrice != null && dsAllPrice.Tables.Count > 0)
                    {
                        foreach (DataRow row in dsAllPrice.Tables[0].Rows)
                        {
                            if (r["ItemCode"].ToString() == row["ItemCode"].ToString())
                            {
                                DataRow rowNew = tblIPO.NewRow();
                                rowNew["ItemCode"] = r["ItemCode"].ToString();
                                rowNew["Dscription"] = r["ItemName"].ToString();
                                rowNew["LB"] = r["LB"].ToString();
                                rowNew["MinStock"] = Math.Round(decimal.Parse(r["MinQty"].ToString()), 2);
                                rowNew["MaxStock"] = Math.Round(decimal.Parse(r["MaxQty"].ToString()), 2);
                                rowNew["BuyUnitMsr"] = row["BuyUnitMsr"];
                                rowNew["Quantity"] = decimal.Parse("0").ToString("#,##0.00");
                                rowNew["ReceivedQty"] = row["ReceivedQty"];
                                if (row["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                                {
                                    rowNew["Price"] = (decimal.Parse(row["NumInBuy"].ToString()) * decimal.Parse(row["Price"].ToString())).ToString("#,##0.00");
                                }
                                else
                                {
                                    rowNew["Price"] = decimal.Parse(row["Price"].ToString()).ToString("#,##0.00");
                                }
                                rowNew["LineTotal"] = decimal.Parse(row["LineTotal"].ToString()).ToString("#,##0.00");
                                rowNew["VatgroupPu"] = row["VatgroupPu"];
                                rowNew["Rate"] = row["Rate"];
                                rowNew["ShipType"] = row["ShipType"];
                                rowNew["TrnspName"] = row["TrnspName"];
                                DataRow[] rCheck = tblIPO.Select("ItemCode='" + r["ItemCode"].ToString() + "'");
                                if (rCheck.Length == 0)
                                {
                                    tblIPO.Rows.Add(rowNew);
                                }
                            }
                        }
                    }
                    //tblIPO = AddNewItem(tblIPO, poDate, r["ItemCode"].ToString(), r["ItemName"].ToString(), r["LB"].ToString(), decimal.Parse(r["MinQty"].ToString()), decimal.Parse(r["MaxQty"].ToString()), this.txtVendorCode.Text, 0);
                }
            }
            Session["ChosenItem"] = dicItem;
            //ReLoad Data
            BindData(tblIPO);
            if (tblIPO.Rows.Count > 0)
            {
                //CalcTotal(tblIPO);
                updateTableTotalPrice();
            }
            this.btnSave.Enabled = true;
            this.btnAddItems.Enabled = true;
            return tblIPO;
        }
        /// <summary>
        /// 
        /// </summary>
        private void UpdatePrice()
        {
            try
            {
                //Update Price
                foreach (DataRow r in ((DataTable)Session["PCH1Table"]).Rows)
                {
                    GetPrice(r);
                }
                BindData((DataTable)Session["PCH1Table"]);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// Update Price
        /// </summary>
        /// <param name="r"></param>
        private void GetPrice(DataRow r)
        {
            try
            {
                DataSet ds = GetDataItem(Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim()), r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblIPO"></param>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="itemName"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataTable AddNewItem(DataTable tblIPO, DateTime poDate, string itemCode, string itemName, string lb, decimal min, decimal max, string venderCode, double quantity)
        {
            try
            {
                DataSet ds = GetDataItem(poDate, itemCode, venderCode, quantity);
                if (ds != null && ds.Tables.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        DataRow rowNew = tblIPO.NewRow();
                        rowNew["ItemCode"] = itemCode;
                        rowNew["Dscription"] = itemName;
                        rowNew["LB"] = lb;
                        rowNew["MinStock"] = Math.Round(min, 2);
                        rowNew["MaxStock"] = Math.Round(max, 2);
                        rowNew["BuyUnitMsr"] = row["BuyUnitMsr"];
                        rowNew["Quantity"] = quantity.ToString("#,##0.00");
                        rowNew["ReceivedQty"] = row["ReceivedQty"];
                        rowNew["Price"] = decimal.Parse(row["Price"].ToString()).ToString("#,##0.00");
                        rowNew["LineTotal"] = decimal.Parse(row["LineTotal"].ToString()).ToString("#,##0.00");
                        rowNew["VatgroupPu"] = row["VatgroupPu"];
                        rowNew["Rate"] = row["Rate"];
                        rowNew["ShipType"] = row["ShipType"];
                        rowNew["TrnspName"] = row["TrnspName"];
                        DataRow[] rCheck = tblIPO.Select("ItemCode='" + itemCode + "'");
                        if (rCheck.Length == 0)
                        {
                            tblIPO.Rows.Add(rowNew);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return tblIPO;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        {
            try
            {
                MasterData obj = new MasterData();
                DataSet ds = new DataSet();
                ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
                return ds;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        private string CheckDate()
        {
            if (this.txtDueDate.Text.Trim().Length > 0 && this.txtPostingDate.Text.Trim().Length > 0)
            {
                if (Utils.AppConstants.isDateTime(this.txtPostingDate.Text) && Utils.AppConstants.isDateTime(this.txtDueDate.Text))
                {
                    if (Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text).Date > Utils.AppConstants.ConvertToDate(this.txtDueDate.Text).Date)
                    {
                        return "Delivery Date cannot earliar than PO Issue Date.";
                    }
                }
                else
                {
                    return "PO Issue Date or Expected Delivery Date is incorrect format.";
                }
            }
            else
            {
                return "PO Issue Date or Expected Delivery Date is not Blank.";
            }
            return string.Empty;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
               string errMess =  CheckDate();
               if (errMess.Length > 0)
               {
                   this.lblError.Text = errMess;
                   this.lblError.Visible = true;
                   return;
               }
                this.lblError.Visible = false;
                this.lblError.Text = "";
                DataSet dsData = new DataSet();
                dsData = CollectDataPO(false);
                if (dsData != null)
                {
                    MasterData obj = new MasterData();
                    DataSet dsResult = null;// obj.CreatePO(_companyCode, this.hdnIsUpdate.Value, _isPO, dsData, false, _docEntry, this.txtVendorCode.Text, "");
                    if (dsResult != null && dsResult.Tables.Count > 0 && dsResult.Tables[0].Rows.Count > 0)
                    {
                        if ((int)dsResult.Tables[0].Rows[0]["ErrCode"] != 0)
                        {
                            string err = dsResult.Tables[0].Rows[0]["ErrMsg"].ToString();
                            if (err.Trim() == "The device is not ready.")
                            {
                                err = "System is processing another request. Pls try again later.";
                            }
                            this.lblError.Text = err;
                        }
                        else
                        {
                            this.lblError.Text = "Operation complete successful!";

                            if (this.hdnIsUpdate.Value == "0")
                            {
                                //ResetPage();
                            }
                           
                        }
                    }
                    else
                    {
                        this.lblError.Text = "System is processing another request. Pls try again later.";
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string CollectData(bool isDraft)
        {
            DocumentXML objInfo = new DocumentXML();
            DataSet ds = CreateData(isDraft);
            if (ds != null)
            {
                Session["SODATA"] = ds.Copy();
                if (isDraft)
                {
                    ds.Tables["ODRF"].Columns.Remove("OutletCode");
                    ds.Tables["DRF1"].Columns.Remove("ShipType");
                    ds.Tables["DRF1"].Columns.Remove("TrnspName");
                    return objInfo.ToXMLStringFromDS("112", ds);
                }
                else
                {
                    ds.Tables["OPOR"].Columns.Remove("OutletCode");
                    ds.Tables["POR1"].Columns.Remove("ShipType");
                    ds.Tables["POR1"].Columns.Remove("TrnspName");
                    return objInfo.ToXMLStringFromDS("22", ds);
                }
            }
            return string.Empty;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isDraft"></param>
        /// <returns></returns>
        public DataSet CollectDataPO(bool isDraft)
        {
            return CreateData(isDraft);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isDraft"></param>
        /// <returns></returns>
        private DataSet CreateData(bool isDraft)
        {
            /*
            try
            {
                DataTable tb = ((DataTable)Session["POTable"]);
                if (tb != null && tb.Rows.Count > 0)
                {
                    DocumentXML objInfo = new DocumentXML();
                    DataSet ds = new DataSet("DS");

                    DataTable tblHeader = new DataTable("OPOR");
                    tblHeader.Columns.Add("CardCode");
                    tblHeader.Columns.Add("CardName");
                    tblHeader.Columns.Add("DocDate");
                    tblHeader.Columns.Add("DocDueDate");
                    tblHeader.Columns.Add("U_AB_PORemarks");
                    tblHeader.Columns.Add("OutletCode");
                    tblHeader.Columns.Add("U_AB_Urgent");
                    tblHeader.Columns.Add("U_AB_UserCode");
                    tblHeader.Columns.Add("U_AB_POWhsCode");
                    if (this.hdnIsUpdate.Value == "0")
                    {
                        tblHeader.Columns.Add("U_AB_SentSupplier");
                    }


                    DataRow row = tblHeader.NewRow();
                    row["CardCode"] = this.txtVendorCode.Text;
                    row["CardName"] = this.txtVendorName.Text;
                    row["DocDate"] = Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim()).ToString("yyyyMMdd");
                    row["DocDueDate"] = Utils.AppConstants.ConvertToDate(this.txtDelDate.Text.Trim()).ToString("yyyyMMdd");
                    row["U_AB_PORemarks"] = this.txtRemarks.Text;
                    
                    row["U_AB_UserCode"] = Session[Utils.AppConstants.ID_User] != null ? Session[Utils.AppConstants.ID_User].ToString() : "";
                    
                    row["U_AB_Urgent"] = this.chkUrgent.Checked ? "Y" : "N";
                    if (this.hdnIsUpdate.Value == "0")
                    {
                        row["U_AB_SentSupplier"] = "N";
                    }
                    //Save As Draft
                    if (isDraft)
                    {
                        tblHeader.Columns.Add("ObjType");
                        row["ObjType"] = "22";
                        tblHeader.TableName = "ODRF";
                    }

                    tblHeader.Rows.Add(row);

                    DataTable tblItem = new DataTable();
                    if (!isDraft)
                    {
                        tblItem.TableName = "POR1";
                    }
                    else
                    {
                        tblItem.TableName = "DRF1";
                    }
                    tblItem.Columns.Add("ItemCode");
                    tblItem.Columns.Add("Dscription");
                    tblItem.Columns.Add("UnitMsr");
                    tblItem.Columns.Add("Quantity");
                    tblItem.Columns.Add("Price");
                    tblItem.Columns.Add("LineTotal");
                    tblItem.Columns.Add("Vatgroup");
                    tblItem.Columns.Add("ShipType");
                    tblItem.Columns.Add("TrnspName");
                    tblItem.Columns.Add("WhsCode");
                    tblItem.Columns.Add("U_AB_POQty");
                    if (isDraft)
                    {
                        tblItem.Columns.Add("PriceBefDi");
                    }
                    foreach (DataRow r in tb.Rows)
                    {
                        DataRow rowNew = tblItem.NewRow();
                        rowNew["ItemCode"] = r["ItemCode"];
                          //Save As Draft
                        if (isDraft)
                        {
                            if (double.Parse(r["Quantity"].ToString()) == 0)
                            {
                                rowNew["Quantity"] = "0.001";
                            }
                            else
                            {
                                rowNew["Quantity"] = r["Quantity"];
                            }
                            rowNew["LineTotal"] = decimal.Parse(rowNew["Quantity"].ToString()) * decimal.Parse(r["Price"].ToString());
                            rowNew["PriceBefDi"] = r["Price"];
                        }
                        else
                        {
                            rowNew["Quantity"] = r["Quantity"];
                            rowNew["LineTotal"] = r["LineTotal"];
                        }
                        rowNew["Dscription"] = r["Dscription"];
                        rowNew["UnitMsr"] = r["BuyUnitMsr"];
                        rowNew["Price"] = r["Price"];
                        rowNew["ShipType"] = r["ShipType"];
                        rowNew["TrnspName"] = r["TrnspName"];
                        rowNew["U_AB_POQty"] = r["Quantity"];
                        rowNew["Vatgroup"] = r["VatgroupPu"];
                        
                        if (!isDraft)
                        {
                            if (double.Parse(r["Quantity"].ToString()) != 0)
                            {
                                tblItem.Rows.Add(rowNew);
                            }
                        }
                        else
                        {
                            tblItem.Rows.Add(rowNew);
                        }
                    }

                    ds.Tables.Add(tblHeader);
                    ds.Tables.Add(tblItem);
                    MasterData obj = new MasterData();
                    string errMsg = string.Empty;
                    if (!isDraft)
                    {
                        if (this.hdnIsUpdate.Value == "0")
                        {
                            //errMsg = obj.CheckAddPO(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(),
                            //                   _companyCode, ds, Utils.AppConstants.ConvertToDate(this.txtDelDate.Text.Trim()).Date, false, string.Empty);
                        }
                        else
                        {
                            //errMsg = obj.CheckAddPO(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(),
                            //              _companyCode, ds, Utils.AppConstants.ConvertToDate(this.txtDelDate.Text.Trim()).Date, true, _docEntry);
                        }
                        if (errMsg.Length > 0)
                        {
                            if (errMsg.Trim() == "The device is not ready.")
                            {
                                errMsg = "System is processing another request. Pls try again later.";
                            }
                            this.lblError.Text = errMsg;
                            this.lblError.Visible = true;
                        }
                        else
                        {
                            DataTable tbAddress = new DataTable();
                            tbAddress.TableName = "POR12";
                            tbAddress.Columns.Add("StreetS");
                            tbAddress.Columns.Add("BlockS");
                            tbAddress.Columns.Add("CityS");
                            tbAddress.Columns.Add("CountryS");
                            tbAddress.Columns.Add("ZipCodes");

                            
                            return ds;
                        }
                    }
                    else
                    {
                        return ds;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }*/
            return null;
        }
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();
                if ( this.hdnStatus.Value.Equals("C") || (ConvertDocType.Get2String(DocType.AP_INVOICE).Equals(hdnBaseType.Value))
                    || (ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO).Equals(hdnBaseType.Value) ))
                {
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    TextBox txtUnitPrice = (TextBox)myRow.FindControl("txtUnitPrice");
                    TextBox txtDiscount = (TextBox)myRow.FindControl("txtDiscount");
                    TextBox txtIncenDisc = (TextBox)myRow.FindControl("txtIncenDisc");
                    TextBox txtDistNumber = (TextBox)myRow.FindControl("txtDistNumber");
                    TextBox txtEngineNumber = (TextBox)myRow.FindControl("txtEngineNumber");

                    if (txtQuantity != null)
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                    if (txtUnitPrice != null)
                    {
                        txtUnitPrice.ReadOnly = true;
                        txtUnitPrice.BackColor = System.Drawing.Color.Transparent;
                        txtUnitPrice.BorderStyle = BorderStyle.None;
                    }
                    if (txtDiscount != null)
                    {
                        txtDiscount.ReadOnly = true;
                        txtDiscount.BackColor = System.Drawing.Color.Transparent;
                        txtDiscount.BorderStyle = BorderStyle.None;
                    }
                    if (txtIncenDisc != null)
                    {
                        txtIncenDisc.ReadOnly = true;
                        txtIncenDisc.BackColor = System.Drawing.Color.Transparent;
                        txtIncenDisc.BorderStyle = BorderStyle.None;
                    }
                    if (txtDistNumber != null)
                    {
                        txtDistNumber.ReadOnly = true;
                        txtDistNumber.BackColor = System.Drawing.Color.Transparent;
                        txtDistNumber.BorderStyle = BorderStyle.None;
                    }
                    if (txtEngineNumber != null)
                    {
                        txtEngineNumber.ReadOnly = true;
                        txtEngineNumber.BackColor = System.Drawing.Color.Transparent;
                        txtEngineNumber.BorderStyle = BorderStyle.None;
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            UpdatePrice();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckValidData((DataTable)Session["PCH1Table"])) return;
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                String requestXML = _collectData();
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateMarketingDocument(requestXML, ConvertDocType.Get2String(DocType.AP_INVOICE), txtDocNo.Text, hdnIsUpdate.Value.Equals("true"), dbType);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    //Close A/P Draft
                    if (hdnBaseType.Value.Equals(ConvertDocType.Get2String(DocType.ALL_DRAFT)))
                    {
                        ts.CloseCancelDocument(ConvertDocType.Get2String(DocType.ALL_DRAFT), txtDocNo.Text, true, dbType);
                    }
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            //try
            //{
            //    Transaction obj = new Transaction();
            //    string error = string.Empty;
            //    if (_isPO == "1")
            //    {
            //        //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
            //    }
            //    else
            //    {
            //        //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
            //    }
            //    if (error.Length == 0)
            //    {
            //        this.lblError.Text = "Operation complete successful!";
            //        DisableControl();
            //    }
            //    else
            //    {
            //        this.lblError.Text = error;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    this.lblError.Text = ex.Message;
            //}
            //this.lblError.Visible = true;
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Taxcode");

            dt.Columns.Add("VatGroup");
            dt.Columns.Add("VatPrcnt");
            dt.Columns.Add("VatSum");

            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("OpenQty");
            dt.Columns.Add("PriceBefDi");
            //dt.Columns.Add("DiscPrcnt");
            dt.Columns.Add("U_Discount");
            dt.Columns.Add("U_IncentiveDiscount");
            dt.Columns.Add("Price");
            dt.Columns.Add("LineTotal");
            dt.Columns.Add("U_VinEngKey");
            dt.Columns.Add("SysNumber");
            dt.Columns.Add("DistNumber");
            dt.Columns.Add("InDate");
            dt.Columns.Add("Notes");
            dt.Columns.Add("WhsCode");

            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");
            dt.Columns.Add("BaseType");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["LineNum"] = dr["LineNum"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Taxcode"] = dr["Taxcode"];
                    row["WhsCode"] = dr["WhsCode"];

                    row["VatGroup"] = dr["VatGroup"];
                    row["VatPrcnt"] = dr["VatPrcnt"];
                    row["VatSum"] = dr["VatSum"];

                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = dr["Quantity"];
                    row["OpenQty"] = dr["OpenQty"];
                    row["PriceBefDi"] = dr["PriceBefDi"];
                    //row["DiscPrcnt"] = dr["DiscPrcnt"];
                    row["U_Discount"] = dr["U_Discount"];
                    row["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"];
                    row["Price"] = dr["Price"]; // Price After Discount
                    row["LineTotal"] = dr["LineTotal"];

                    if (dr.Table.Columns.Contains("DistNumber") && !ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO).Equals(hdnBaseType.Value) )
                    {
                        row["SysNumber"] = dr["SysNumber"];
                        row["DistNumber"] = dr["DistNumber"];
                        row["InDate"] = dr["InDate"];
                        row["Notes"] = dr["Notes"];
                        row["U_VinEngKey"] = dr["SysNumber"].ToString() + ";" + dr["DistNumber"].ToString() + ";" + dr["Notes"].ToString() + ";;" + dr["InDate"].ToString();
                    }
                    else if (ConvertDocType.Get2String(DocType.ALL_DRAFT).Equals(hdnBaseType.Value))
                    {
                        string[] lsArr = dr["U_VinEngKey"].ToString().Split(';');
                        row["SysNumber"] = "1";
                        row["DistNumber"] = lsArr[0];
                        row["Notes"] = lsArr[1];
                        row["InDate"] = lsArr[3];
                        row["U_VinEngKey"] = dr["U_VinEngKey"];
                    }

                    row["BaseType"] = dr["BaseType"];
                    row["BaseEntry"] = dr["BaseEntry"];
                    row["BaseLine"] = dr["BaseLine"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadDefault()
        {
            this.lblStatus.Text = "Open";
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDueDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocNo.Text = 
            this.txtConpersonName.Text =
            this.txtVendorCode.Text =
            this.txtVendorName.Text = 
            this.txtRemarks.Text = 
            this.hdnBaseType.Value = string.Empty;
            // Binding data Buyer
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            ((GeneralFunctions)Session["APGF"]).BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");

            this.lblSubTotal.Text = 
            this.lblTaxAmount.Text = 
            this.lblDocumentTotal.Text = "0";

            DataTable dtContents = BuildContents((DataTable)Session["PCH1Table"]);
            BindData(dtContents);
        }

        protected void LoadData(String apinvId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = null;
            if (ConvertDocType.Get2String(DocType.AP_INVOICE) != NewDocType) // In-case: copy from
                returnDoc = ts.GetMarketingDocument_OpenStatus(NewDocType, apinvId, dbType);
            else returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, apinvId, dbType);

            if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType); // apinvId = "1";
 
            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtHeader = returnDoc.Tables[0];
            DataRow dr = dtHeader.Rows[0];
            this.txtVendorName.Text = dr["CardName"].ToString();
            this.txtVendorCode.Text = dr["CardCode"].ToString();
            this.txtDocNo.Text = dr["DocEntry"].ToString();
            if (dr["DocStatus"].ToString().Equals("C"))
            {
                this.lblStatus.Text = "Closed";
                SetScreenStatus("Close");
            }
            else if (dr["DocStatus"].ToString().Equals("O"))
            {
                this.lblStatus.Text = "Open";
                if (NewDocType != ConvertDocType.Get2String(DocType.AP_INVOICE))
                    SetScreenStatus("New");
                else SetScreenStatus("Update");
            }
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")) );
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            txtDueDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtHeader.Rows[0]["DocDueDate"], new CultureInfo("es-US")));
            txtInvNo.Text = dr["U_PInvoiceNBR"].ToString();
            txtSeriesNo.Text = dr["U_PKyhieu"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();
            // Binding data Buyer
            ((GeneralFunctions)Session["APGF"]).BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, dr["SlpCode"].ToString());

            hdnBaseType.Value = NewDocType;
            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            if (ConvertDocType.Get2String(DocType.AP_INVOICE) != NewDocType) // In this case: copy from
            {
                foreach (DataRow row in dtContents.Rows)
                {
                    updateRowTotalPrice(row);
                    row["BaseEntry"] = apinvId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                    row["Quantity"] = row["OpenQty"];
                }
            }
            else
                foreach (DataRow row in dtContents.Rows)
                    updateRowTotalPrice(row);
                            
            BindData(dtContents);
            updateTableTotalPrice();
        }

        private void BuildSRNT(ref DataTable dtSRNT, string ItemCode, string SysNumber, string DistNumber, string InDate, string Notes,
    double Quantity, string WhsCode, string DocType, string DocEntry, string DocLineNum)
        {
            if (dtSRNT == null)
            {
                dtSRNT = new DataTable("SRNT");
                dtSRNT.Columns.Add("ItemCode");
                dtSRNT.Columns.Add("SysNumber");    // Default
                dtSRNT.Columns.Add("DistNumber");   // VIN Number
                dtSRNT.Columns.Add("InDate");       // Get default
                dtSRNT.Columns.Add("Quantity");     // 1
                dtSRNT.Columns.Add("WhsCode");      // Default
                dtSRNT.Columns.Add("DocType");      // 13
                dtSRNT.Columns.Add("DocEntry");     // Get from Incoming Payment No.
                dtSRNT.Columns.Add("DocLineNum");   // 1
                dtSRNT.Columns.Add("Notes");   // 
                //dtSRNT.Columns.Add("BSubLineNo");   // LineNo
            }

            DataRow drSRNT = dtSRNT.NewRow();
            drSRNT["ItemCode"] = ItemCode;      // INV1
            drSRNT["SysNumber"] = SysNumber;
            drSRNT["DistNumber"] = DistNumber;   // VIN Number
            drSRNT["InDate"] = Utils.AppConstants.ConvertToDate(InDate).ToString("yyyyMMdd");
            drSRNT["Quantity"] = Quantity;       // INV1
            drSRNT["WhsCode"] = WhsCode;         // INV1
            drSRNT["DocType"] = DocType;         // INV1
            drSRNT["DocEntry"] = DocEntry;       // INV1
            drSRNT["DocLineNum"] = DocLineNum;   // INV1
            drSRNT["Notes"] = Notes;
            //drSRNT["BSubLineNo"] = BSubLineNo; // INV1
            dtSRNT.Rows.Add(drSRNT);
        }

        public String _collectData()
        {
            try
            {
                GeneralFunctions GF = (GeneralFunctions)Session["APGF"];
                DataTable dtContents = (DataTable)Session["PCH1Table"];

                //Update table header
                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series");
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("SlpCode");
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");

                dtHeader.Columns.Add("U_PInvoiceNBR");
                dtHeader.Columns.Add("U_PKyhieu");

                DataRow drHeader = dtHeader.NewRow();
                if (hdnIsUpdate.Value.Equals("true")) // Update
                {
                    drHeader["DocEntry"] =
                    drHeader["DocNum"] = int.Parse(txtDocNo.Text);
                }
                else // Add new
                {
                    drHeader["Series"] = 9;
                    drHeader["DocStatus"] = "O";
                }

                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(txtDueDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["CardCode"] = txtVendorCode.Text;
                drHeader["CardName"] = txtVendorName.Text.Trim();
                
                drHeader["Comments"] = txtRemarks.Text.Trim();
                drHeader["SlpCode"] = ddlBuyer.SelectedValue;
                //dr["JrnlMemo"] = txtJournalRemark.Text;
                drHeader["U_ContactPerson"] = txtConpersonName.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;
                drHeader["U_PInvoiceNBR"] = txtInvNo.Text.Trim();
                drHeader["U_PKyhieu"] = txtSeriesNo.Text.Trim();

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;

                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("UomCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("PriceBefDi");

                dt.Columns.Add("VatGroup");
                dt.Columns.Add("VatPrcnt");
                //
                dt.Columns.Add("VatSum");
                dt.Columns.Add("U_Discount");
                dt.Columns.Add("U_IncentiveDiscount");
                dt.Columns.Add("U_VinEngKey");

                //dt.Columns.Add("DiscPrcnt");
                dt.Columns.Add("Price");
                dt.Columns.Add("LineTotal");

                DataTable dtSRNT = null;
                if (!String.IsNullOrEmpty(hdnBaseType.Value) && !hdnBaseType.Value.Equals(ConvertDocType.Get2String(DocType.ALL_DRAFT)))
                {
                    dt.Columns.Add("BaseEntry");
                    dt.Columns.Add("BaseLine");
                    dt.Columns.Add("BaseType");
                }

                if (dtContents != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        DataRow row = dt.NewRow();
                        if (hdnIsUpdate.Value.Equals("true")) row["DocEntry"] = int.Parse(txtDocNo.Text);
                        row["LineNum"] = liNo;
                        row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];

                        row["Dscription"] = dr["Dscription"];
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["UomCode"] = dr["UomCode"];
                        row["Quantity"] = dr["Quantity"];
                        row["PriceBefDi"] = dr["PriceBefDi"];

                        row["WhsCode"] = dr["WhsCode"];

                        row["VatGroup"] = dr["VatGroup"];
                        row["VatPrcnt"] = dr["VatPrcnt"];
                        row["VatSum"] = dr["VatSum"];
                        row["U_Discount"] = dr["U_Discount"];
                        row["U_IncentiveDiscount"] = dr["U_IncentiveDiscount"];
                        row["U_VinEngKey"] = dr["U_VinEngKey"];

                        //row["DiscPrcnt"] = dr["DiscPrcnt"];
                        row["Price"] = dr["Price"]; // Price After Discount
                        row["LineTotal"] = dr["LineTotal"];

                        if (!String.IsNullOrEmpty(hdnBaseType.Value) && !hdnBaseType.Value.Equals(ConvertDocType.Get2String(DocType.ALL_DRAFT)))
                        {
                            row["BaseEntry"] = dr["BaseEntry"];
                            row["BaseLine"] = dr["BaseLine"];
                            row["BaseType"] = dr["BaseType"];
                        }
                        if (!ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO).Equals(hdnBaseType.Value))
                        {
                            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                            if (!GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["ItemCode"].ToString()).Equals("104"))
                                BuildSRNT(ref dtSRNT, dr["ItemCode"].ToString(), "", dr["DistNumber"].ToString(), txtPostingDate.Text.Trim(),
                                    dr["Notes"].ToString(), double.Parse(dr["Quantity"].ToString()), dr["WhsCode"].ToString(), ConvertDocType.Get2String(DocType.AP_INVOICE), txtDocNo.Text, liNo.ToString());
                        }

                        dt.Rows.Add(row);
                        liNo++;
                    }
                }

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());

                Array arrContentsCols = new string[] { "Quantity", "PriceBefDi", "Price", "VatPrcnt", "VatSum", "U_Discount", "U_IncentiveDiscount", "LineTotal" }; // Columns need to reset format numeric
                ds.Tables.Add(GF.ResetFormatNumeric(dt, arrContentsCols).Copy());
                if(!ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO).Equals(hdnBaseType.Value))
                    ds.Tables.Add(dtSRNT.Copy());

                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.AP_INVOICE), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }

        protected void updateTableTotalPrice()
        {
            GeneralFunctions GF = (GeneralFunctions)Session["APGF"];
            double orderTotalBeforeDiscount = 0.0, orderTotal = 0.0, taxTotal = 0.0;
            DataTable dtContents = (DataTable)Session["PCH1Table"];

            foreach (DataRow row in dtContents.Rows)
            {
                if (!"".Equals(row["ItemCode"]))
                {
                    double total = GF.Object2Double((object)GF.ResetFormatNumeric(row["LineTotal"].ToString()), "SumDec");
                    double taxRate = GF.Object2Double(row["VatPrcnt"], "RateDec");
                    if (taxRate == 0) taxRate = 10;
                    double tax = total * taxRate / 100;

                    orderTotalBeforeDiscount += total;
                    taxTotal += tax;
                }
            }
            this.lblSubTotal.Text = GF.FormatNumeric(orderTotalBeforeDiscount.ToString(), "SumDec");
            this.lblTaxAmount.Text = GF.FormatNumeric(taxTotal.ToString(), "SumDec");
            orderTotal = orderTotalBeforeDiscount + taxTotal;
            this.lblDocumentTotal.Text = GF.FormatNumeric(orderTotal.ToString(), "SumDec");
        }

        public void updateRowTotalPrice(DataRow row)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["APGF"];
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, totalBefDisc = 0;
            double VatPrcnt = 0, VatSum = 0, U_Discount = 0, U_IncentiveDiscount = 0, TotalAfDisc = 0, Total = 0;

            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");

            //discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            // VatPrcnt, U_Discount, U_IncentiveDiscount
            VatPrcnt = GF.Object2Double(GF.ResetFormatNumeric(row["VatPrcnt"].ToString()), "PercentDec");
            U_Discount = GF.Object2Double(GF.ResetFormatNumeric(row["U_Discount"].ToString()), "SumDec");
            U_IncentiveDiscount = GF.Object2Double(GF.ResetFormatNumeric(row["U_IncentiveDiscount"].ToString()), "SumDec");

            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");
            totalBefDisc = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            // Total after discount
            TotalAfDisc = totalBefDisc - (U_Discount + U_IncentiveDiscount);
            // VatSum
            VatSum = (TotalAfDisc * VatPrcnt) / 100;
            // Total
            Total = (TotalAfDisc + VatSum);

            //total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            //row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");
            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["VatSum"] = GF.FormatNumeric(VatSum.ToString(), "SumDec");
            row["LineTotal"] = GF.FormatNumeric(Total.ToString(), "SumDec");
            row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
        }

        protected void ClearScreen()
        {
            /*dtHeader = new DataTable(TblHeaderName);
            dtHeader.Columns.Add("CardCode");
            dtHeader.Columns.Add("CardName");

            dtHeader.Columns.Add("DocStatus");
            dtHeader.Columns.Add("TaxDate");
            dtHeader.Columns.Add("DocDate");
            dtHeader.Columns.Add("DocDueDate");
            dtHeader.Columns.Add("Comments");
            dtHeader.Columns.Add("U_ContactPerson");
            dtHeader.Rows.Add();*/

            // Binding data Buyer
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            GF.BindDataSaleMan(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlBuyer, "-1");
            Session["APGF"] = null;
            Session["PCH1Table"] = null;

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDueDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci); // DocDate

            txtInvNo.Text =
            txtSeriesNo.Text =
            txtRemarks.Text =
            txtVendorCode.Text =
            txtVendorName.Text = 
            txtConpersonName.Text = 
            hdnBaseType.Value = String.Empty; 

            this.lblSubTotal.Text =
            this.lblTaxAmount.Text =
            this.lblDocumentTotal.Text = "0";

            DataTable dtContents = BuildContents((DataTable)Session["PCH1Table"]);
            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAddItems.Enabled = false;
                    btnSave.Enabled = 
                    btnCopyFrom.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    break;
                case "Update":
                    hdnIsUpdate.Value = "true";
                    btnAddItems.Enabled = 
                    btnSave.Enabled = 
                    btnCopyFrom.Enabled = true;
                    break;
                case "Close":
                    btnAddItems.Enabled = 
                    btnSave.Enabled = 
                    btnCopyFrom.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    break;
            }
        }

        private bool CheckValidData(DataTable dtPCH1)
        {
            bool smooth = true;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            if (ConvertDocType.Get2String(DocType.GOODS_RECEIPT_PO).Equals(hdnBaseType.Value)) return smooth;
            foreach (DataRow dr in dtPCH1.Rows)
            {
                if (((GeneralFunctions)Session["APGF"]).GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), dr["ItemCode"].ToString()).Equals("104")) continue;
                if (string.IsNullOrEmpty(dr["DistNumber"].ToString()))
                {
                    this.lblError.Text = " VIN Number cannot be empty. Please input VIN Number for '" + dr["ItemCode"].ToString() + "' item.";
                    this.lblError.Visible = true;
                    smooth = false;
                    break;
                }
                if ( string.IsNullOrEmpty(dr["Notes"].ToString()))
                {
                    this.lblError.Text = " Engine Number cannot be empty. Please input Engine Number for '" + dr["ItemCode"].ToString() + "' item.";
                    smooth = false;
                    break;
                }
            }
            return smooth;
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsDocNo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER, 
                Session[Utils.AppConstants.ID_Dealer].ToString(), 
                Utils.AppConstants.SALES,
                ConvertDocType.Get2String(DocType.AP_INVOICE), 
                TblHeaderName, HeaderKeyName
            );
            if (txtDocNo.Text.CompareTo(lsDocNo) != 0) Response.Redirect(CurrentPageUrl + "?apinv_id=" + lsDocNo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label lblModel = (Label)row.FindControl("lblModel");
                lblModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = ((GeneralFunctions)Session["APGF"]).GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, string.Empty);

                    Label lblProduct = (Label)row.FindControl("lblProduct");
                    lblProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label lblProduct = (Label)row.FindControl("lblProduct");
                lblProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label lblColor = (Label)row.FindControl("lblColor");
                lblColor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblPCH1 = (DataTable)Session["PCH1Table"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtItem = ((GeneralFunctions)Session["APGF"]).GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataSet defaultInfo = defaultWS.GetDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtVendorCode.Text, dtItem.Rows[0]["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.SALES);
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                    {
                        DataRow drDefaultLine = defaultInfo.Tables[0].Rows[0];
                        rowUpdate = tblPCH1.Select("No=" + lblNo.Text);
                        if (rowUpdate.Length == 1)
                        {
                            rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                            rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                            rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                            rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                            rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                            rowUpdate[0]["Quantity"] = 1;

                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["UnitPrice"];
                            rowUpdate[0]["DiscPrcnt"] = drDefaultLine["Discount"];
                            rowUpdate[0]["PriceBefDi"] = drDefaultLine["PriceAfDi"];
                            rowUpdate[0]["TaxCode"] = drDefaultLine["TaxCode"];
                            rowUpdate[0]["VatPrcnt"] = drDefaultLine["TaxRate"];
                        }
                    }
                }
                else
                {
                    rowUpdate = tblPCH1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Quantity"] = 1;

                    rowUpdate[0]["PriceBefDi"] = 0;
                    rowUpdate[0]["DiscPrcnt"] = 0;
                    rowUpdate[0]["PriceBefDi"] = 0;
                    rowUpdate[0]["TaxCode"] = string.Empty;
                    rowUpdate[0]["VatPrcnt"] = 0;
                }
                updateRowTotalPrice(rowUpdate[0]);
                BindData(tblPCH1);
            }
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbPCH1 = (DataTable)Session["PCH1Table"];
            DataRow rowNew = tbPCH1.NewRow();
            rowNew["No"] = (tbPCH1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["PriceBefDi"] = 0;
            rowNew["DiscPrcnt"] = 0;
            rowNew["PriceBefDi"] = 0;
            rowNew["TaxCode"] = string.Empty;
            rowNew["VatPrcnt"] = 0;
            tbPCH1.Rows.Add(rowNew);
            BindData(tbPCH1);
        }

    }
}